const fs = require('fs');
const path = require('path');
const fetch = require('node-fetch');

const conf = require('../conf');

// 下载已打卡的健康码原图
(async () => {
    const daka_day = '2022-03-31'; // 目标日期
    const check2dakaNew2 = await fetch('https://a.welife001.com/applet/notify/check2dakaNew2', {
        method: 'POST',
        headers: {
            'Host': 'a.welife001.com',
            'Connection': 'keep-alive',
            'Content-Type': 'application/json', // content-length不要传，传正确的反而报错
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat',
            'Referer': 'https://servicewechat.com/wx23d8d7ea22039466/616/page-frame.html',
            'imprint': conf.openId,
        },
        body: JSON.stringify({
            "_id": '622d4679bf3de32fad294f4f', // invest id
            "cid": '5ec61a18902cc93eade35e73', // memberId
            "daka_day": daka_day,
            "click_load": false,
            "teacher_cate": "",
            "member_id": conf.memberId,
            "cls_ts": new Date().getTime(),
        }),
    }).then(res => res.json());
    console.log(JSON.stringify(check2dakaNew2, null, 2))
    await download(daka_day, 'child', check2dakaNew2.data.accepts[0].answer.subject[2].input.file[0]);
    // await download(daka_day, 'mama', check2dakaNew2.data.accepts[0].answer.subject[7].input.file[0]);
    await download(daka_day, 'baba', check2dakaNew2.data.accepts[0].answer.subject[7].input.file[0]);
})().catch(err => console.log(err));

async function download(daka_day, name, f) {
    const dir = path.join(__dirname, 'history');
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
    }
    const url = `https://img.welife001.com/${f.id}?_=${Date.now()}`;
    const file = path.join(dir, `${daka_day}_${name}${path.extname(f.id)}`);
    console.log('==> GET', url);
    await fetch(url).then(res => {
        console.log('<==', res.status, res.statusText);
        return res.body.pipe(fs.createWriteStream(file));
    });
    console.log('==>', file);
}